//
//  QDMessageMainViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/24.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit
import HandyJSON
import Kingfisher

/// 消息分类 的控制器
final class QDMessageMainViewController: NWTableViewController,QDLargeTitleTableHeaderScrollable {

    //导航rightItem
    lazy var rightButtonItem: UIBarButtonItem = {
        
        let button = UIButton()
        button.setTitle("全部已读", for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.setTitleColor(QDColors.theme, for: .normal)
        button.titleLabel?.font = Font.regular.font(size: 14)
        button.addTarget(self, action: #selector(allRead), for: .touchUpInside)
        self.button = button
        
        return UIBarButtonItem(customView: button)
    }()
    /// 导航rightItem的button
    weak var button: UIButton?
    
    /// 大标题
    var largeTableHeaderView = QDLargeButtonTableHeaderView()
    
    /// 分类列表数据源
    var rows = [QDNetworkingManager.QDMsgCateListRow]()
    /// 是否存在未读
    var hasUnRead = true {
        willSet {
            largeTableHeaderView.button.isHidden = !newValue
            if !newValue {
                navigationItem.rightBarButtonItem = nil
            }
        }
    }

    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        tableView.rowHeight = 80
        headerRefreshEnable = false
        footerRefreshEnable = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        largeTableHeaderView.title = "消息分类"
        largeTableHeaderView.buttonTitle = "全部已读"
        
        largeTableHeaderView.frame = CGRect(origin: .zero, size: CGSize(width: ritl_width, height: QDLargeTitleTableHeaderViewNormalHeight + 8))
        largeTableHeaderView.button.addTarget(self, action: #selector(allRead), for: .touchUpInside)
        
        tableView.tableHeaderView = largeTableHeaderView
        
        /// 请求消息列表
        requestAllMsgList()
    }
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDMessageTableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setNavigationBarShadowViewHidden(navigationItem.title == nil)
    }
    
    //MARK: NavigationBar
    override var nav_mutableBarShadowHidden: Bool { return true }
    override var nav_tintColor: UIColor { return QDColors.separator}
    
    
    //MARK: Action - Target
    
    /// 全部已读
    @objc func allRead() {

        //判断是否存在未读消息
        if (!hasUnRead) {
            view.showTextHUD(text: "没有未读信息!"); return
        }
        
        QDNetworkingManager.request(url: msgReadAllUrl, success: { (msg, data) in
            
            /// 全部置为已读
            for i in 0..<self.rows.count {
                self.rows[i].readAll()
            }
            
            self.hasUnRead = false
            self.tableView.reloadData()
            
        }) { (msg, errorType) in

        }
    }
    
    //MARK: UIScrollView
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        tableViewDidScroll(contentOfset: scrollView.contentOffset) { (isShow) in
            setNavigationBarShadowViewHidden(!isShow)
            if hasUnRead { // 存在未读信息
                navigationItem.rightBarButtonItem = isShow ? self.rightButtonItem : nil
            }
        }
    }
    
    //MARK: UITableViewCell
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rows.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let cateCell = cell as? QDMessageTableViewCell {
            let cateList = rows[indexPath.row]
            
            //进行赋值
            cateCell.headerImageView.kf.setImage(with:URL(string: cateList.imgUrl))
            cateCell.titleLabel.text = cateList.typeName
            cateCell.timeLabel.text = cateList.time
            cateCell.subtitleLabel.text = cateList.message
            cateCell.badgeLabel.isHidden = !cateList.hasMessageUnRead
            cateCell.badgeLabel.text = "\(cateList.messageNum)"
        }
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let cateList = rows[indexPath.row]
        
        // 阅读完毕
        let readComplete = {
            //修改数据
            self.rows[indexPath.row].readAll()
            //刷新自己的数据
            self.tableView.reloadData()
            //修改已读方式
            self.hasUnRead = self.rows.filter{ $0.messageNum > 0 }.count > 0
        }
        // 进入消息列表
        router(platform: .messageList(type: cateList.typeId, typeName: cateList.typeName, hasUnread: cateList.messageNum > 0, readComplete: readComplete))
    }
}

extension QDMessageMainViewController {
    
    /// 请求所有的分类列表
    private func requestAllMsgList(){
        
        view.showWatingHUD()
        
        /// 请求
        QDNetworkingManager.requestMsgCateList(success: { (hasRead, rows) in
            
            self.view.dismissHUD()
            self.hasUnRead = !hasRead; //true表示没有，false表示有未读
            self.rows = rows
            self.tableView.reloadData()
            
        }) { (msg, errorType) in
            
            self.view.showTextHUD(text: msg)
        }
    }
}



// MARK: Request
extension QDNetworkingManager {
    
    struct QDMsgCateListRow: HandyJSON {
        /// 消息分类类型
        var typeId = ""
        /// 分类名称
        var typeName = ""
        /// 未读数量
        var messageNum = 0
        /// 图片
        var imgUrl = ""
        /// 是否存在未读
        var hasMessageUnRead: Bool {
            get {
                return messageNum > 0
            }
        }
        /// 最近一次的时间
        var time = ""
        /// 消息
        var message = ""
        
        mutating func readAll(){
            messageNum = 0
        }
    }
    
    
    struct QDMsgCateListContainer: HandyJSON  {
        /// 是否存在未读
        var hasRead = false
        /// 消息列表
        var messageData = [QDMsgCateListRow]()
        
        
        mutating func mapping(mapper: HelpingMapper) {
//            mapper <<<
//                self.hasRead <-- "isRead"
            
            mapper <<<
                self.hasRead <-- "read"
        }
    }
    
    /// 请求消息的分类列表
    static func requestMsgCateList(success:@escaping ((Bool,[QDMsgCateListRow]) ->()),fail: QDNetworkingError?){
        
        
        request(url: msgCateUrl, success: { (msg, data) in
            
            guard let container = QDMsgCateListContainer.deserialize(from: data) else {
                fail?("数据格式不正确",.unNormal); return
            }
            //返回数据
            success(container.hasRead,container.messageData)
            
        }) { (msg, errorType) in
            
            fail?(msg,errorType)
        }
    }
}

